package io.renren.modules.medical.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.MedicalException;
import io.renren.common.result.ResultCodeEnum;
import io.renren.common.utils.DoctorInfoUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.medical.dao.PatientDoctorRelativeDao;
import io.renren.modules.medical.entity.DoctorInfoEntity;
import io.renren.modules.medical.entity.IllSubEntity;
import io.renren.modules.medical.entity.PatientDoctorRelativeEntity;
import io.renren.modules.medical.service.DoctorInfoService;
import io.renren.modules.medical.service.IllSubService;
import io.renren.modules.medical.service.PatientDoctorRelativeService;
import io.renren.modules.medical.vo.medicalVo.IllSubTitleAndIdVo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service("patientDoctorRelativeService")
public class PatientDoctorRelativeServiceImpl extends ServiceImpl<PatientDoctorRelativeDao, PatientDoctorRelativeEntity> implements PatientDoctorRelativeService {

    private final IllSubService illSubService;

    private final DoctorInfoService doctorInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PatientDoctorRelativeEntity> page = this.page(
                new Query<PatientDoctorRelativeEntity>().getPage(params),
                new QueryWrapper<PatientDoctorRelativeEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<IllSubEntity> getChildrenByParentId(Long depId, Long patientId) {
        // 如果是膝关节炎医生的话就直接返回膝关节的基础信息
        boolean isGonitis = DoctorInfoUtils.isGonitis(depId, illSubService);
        if (depId != 0 && isGonitis) {
            // 先查看当前病人是不是已经有过膝关节炎的记录，因为膝关节炎有相应的疾病信息表
            List<Long> gonitisIds = illSubService.getChildrenAndParent(depId);
            LambdaQueryWrapper<PatientDoctorRelativeEntity> patientDoctorRelativeWrapper = new LambdaQueryWrapper<>();
            patientDoctorRelativeWrapper.eq(PatientDoctorRelativeEntity::getPatientId, patientId);
            patientDoctorRelativeWrapper.in(PatientDoctorRelativeEntity::getSubId, gonitisIds);
            int count = this.count(patientDoctorRelativeWrapper);
            if (count >= 1) {
                throw new MedicalException(ResultCodeEnum.NOT_FIND_ERROR.getCode(), "该患者已有该病情信息");
            }
            // 再返回膝关节炎父级
            ArrayList<IllSubEntity> gonitisList = new ArrayList<>();
            gonitisList.add(illSubService.getById(depId));
            return gonitisList;
        } else {
            // 如果是除开膝关节炎以外的病情，返回的是没有添加过的病情分类
            LambdaQueryWrapper<IllSubEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(IllSubEntity::getParentId, depId);
            List<IllSubEntity> illSubList = illSubService.list(queryWrapper);
            illSubList = illSubList.stream().filter(item -> {
                Long subId = item.getId();
                LambdaQueryWrapper<PatientDoctorRelativeEntity> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(PatientDoctorRelativeEntity::getPatientId, patientId);
                wrapper.eq(PatientDoctorRelativeEntity::getSubId, subId);
                int count = this.count(wrapper);
                return count == 0;
            }).collect(Collectors.toList());

            return illSubList;
        }

    }

    /**
     * 根据filter中的病人id获取到病人所有的病情分类集合
     *
     */
    // TODO 动态获取用户Id 待修改
    @Override
    public List<IllSubTitleAndIdVo> getPatientIllSub() {
        Long patientInfoId = 6L;
        Long gonitisSubId = 32L; // 膝关节炎的病情Id
        LambdaQueryWrapper<PatientDoctorRelativeEntity> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(PatientDoctorRelativeEntity::getPatientId, patientInfoId);
        List<PatientDoctorRelativeEntity> relativeList = this.list(wrapper1);

        // 获取到所有的病情集合
        LambdaQueryWrapper<IllSubEntity> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(IllSubEntity::getParentId, gonitisSubId);
        List<IllSubEntity> illSubEntities = illSubService.list(wrapper2);
        List<Long> subIdList = illSubEntities.stream().map(IllSubEntity::getId).collect(Collectors.toList());

        // 查询为null就直接退出
        if (relativeList == null) {
            return new ArrayList<IllSubTitleAndIdVo>();
        }

        List<IllSubTitleAndIdVo> resultList = relativeList.stream().map(item -> {
            Long subId = item.getSubId();
            if (subIdList.contains(subId)) {
                IllSubTitleAndIdVo illSubTitleAndIdVo = new IllSubTitleAndIdVo();
                illSubTitleAndIdVo.setTitle(item.getSubTitle());
                illSubTitleAndIdVo.setId(item.getSubId());
                return illSubTitleAndIdVo;
            }
            return null;
        }).collect(Collectors.toList());

        return resultList;
    }

    @Override
    public void addPatientSub(PatientDoctorRelativeEntity patientDoctorRelativeEntity) {
        Long patientId = patientDoctorRelativeEntity.getPatientId();
        Long subId = patientDoctorRelativeEntity.getSubId();
        if (patientId == null || subId == null) {
            throw new MedicalException(ResultCodeEnum.MODEL_INVALID_ERROR.getCode(), ResultCodeEnum.MODEL_INVALID_ERROR.getMessage());
        }
        // 先看病人是不是有该病情
        LambdaQueryWrapper<PatientDoctorRelativeEntity> patientDoctorRelativeWrapper = new LambdaQueryWrapper<>();
        patientDoctorRelativeWrapper.eq(PatientDoctorRelativeEntity::getPatientId, patientId);
        patientDoctorRelativeWrapper.eq(PatientDoctorRelativeEntity::getSubId, subId);
        int count = this.count(patientDoctorRelativeWrapper);
        if (count >= 1) {
            throw new MedicalException(ResultCodeEnum.PATIENT_SUB_REPETITION.getCode(), ResultCodeEnum.PATIENT_SUB_REPETITION.getMessage());
        }
        IllSubEntity illSubEntity = illSubService.getById(subId);
        // 新增
        DoctorInfoEntity doctorInfo = DoctorInfoUtils.getDoctorInfo(doctorInfoService);
        patientDoctorRelativeEntity.setDoctorId(doctorInfo.getId());
        patientDoctorRelativeEntity.setPatientId(patientId);
        patientDoctorRelativeEntity.setSubTitle(illSubEntity.getTitle());
        patientDoctorRelativeEntity.setSubId(illSubEntity.getId());
        this.save(patientDoctorRelativeEntity);
    }

}